package controllers

import (
	"dog/cache"
	"dog/models"
	"dog/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type Usercontroller struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Usercontroller) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "账号密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	user := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}

	if err := models.DB.Create(&user).Error; err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "注册成功",
		Data: user,
	}
	c.ServeJSON()
}

func (c *Usercontroller) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "账号密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	key := "user_login_error" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "密码错误次数过多,封禁用户2小时",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "登录成功",
			Data: user,
		}
		c.ServeJSON()
		return
	}
}
